package com.xinghou.platform.dao.main.aspect;

import com.google.gson.reflect.TypeToken;
import com.xinghou.platform.dao.main.common.DBDataConfigLevelCached;
import com.xinghou.platform.model.main.DataConfig;
import com.xinghou.platform.model.main.User;
import com.xinghou.platform.util.JsonUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.xml.crypto.Data;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by qingshengzheng on 16/7/7.
 */
@Aspect
@Component
public class DataConfigCacheAspect extends DBDataConfigLevelCached {
    @Pointcut("execution(public * com.xinghou.platform.dao.main.DataConfigDAO.getDataConfigList(..))")
    public void getDataConfigList() {
    }
    @Around("getDataConfigList()")
    public List<DataConfig> getDataConfigByTag_id(ProceedingJoinPoint pjp) throws Throwable {
        String type = ((Object[]) pjp.getArgs())[0].toString();
        String key = String.format(CACHE_DATA_CONFIG, type);
        Object jsonToken = getRedisClient().get(key, CACHED_DB_INDEX);
        if(jsonToken == null){
            List<DataConfig> dataconfigs = (List<DataConfig> )pjp.proceed();
            if(dataconfigs != null)
                getRedisClient().set(key, JsonUtil.toJson(dataconfigs), CACHED_DB_INDEX);
            return dataconfigs;
        }else{
            List<DataConfig> dataconfigs = (List<DataConfig>)JsonUtil.fromJson(jsonToken.toString(), new TypeToken<List<DataConfig>>() {  }.getType());
            return dataconfigs;
        }
    }
}
